package com.cvmars.jianyou.module.activity;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cvmars.jianyou.R;
import com.cvmars.jianyou.api.api.Api;
import com.cvmars.jianyou.api.api.HttpUtils;
import com.cvmars.jianyou.api.api.SimpleSubscriber;
import com.cvmars.jianyou.api.model.HttpResult;
import com.cvmars.jianyou.config.MyConfig;
import com.cvmars.jianyou.model.ImageModel;
import com.cvmars.jianyou.model.UserModel;
import com.cvmars.jianyou.module.adapter.AddressAdapter;
import com.cvmars.jianyou.module.base.BasePictureActivity;
import com.cvmars.jianyou.ui.CircleImageView;
import com.cvmars.jianyou.utils.ImageUtils;
import com.cvmars.jianyou.utils.NetworkUtil;
import com.cvmars.jianyou.utils.QiNiuUtils;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citylist.Toast.ToastUtils;
import com.lljjcoder.style.citypickerview.CityPickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.orhanobut.hawk.Hawk;
import com.suke.widget.SwitchButton;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.UserInfo;

public class MeInfoActivity extends BasePictureActivity {


    @BindView(R.id.me_info_avatar_lay)
    LinearLayout meInfoAvatarLay;
    @BindView(R.id.rl_info_sex)
    RelativeLayout rlInfoSex;
    @BindView(R.id.rl_address)
    RelativeLayout rlAddress;
    @BindView(R.id.me_info_avatar)
    CircleImageView meInfoAvatar;

    //申明对象
    CityPickerView mPicker = new CityPickerView();
    @BindView(R.id.txt_info_workaddress)
    TextView txtInfoWorkaddress;
    @BindView(R.id.rl_workaddress)
    RelativeLayout rlWorkaddress;
    @BindView(R.id.txt_info_address)
    TextView txtInfoAddress;
    @BindView(R.id.parent_layout)
    LinearLayout parentLayout;
    @BindView(R.id.txt_info_sex)
    TextView txtInfoSex;

    AddressAdapter homeAdapter;
    @BindView(R.id.txt_info_name)
    TextView txtInfoName;
    @BindView(R.id.txt_info_birthday)
    TextView txtInfoBirthday;

    public int ageType;//性别： 0：未设置， 1：男， 2：女
    @BindView(R.id.rl_name)
    RelativeLayout rlName;

    @BindView(R.id.rl_birthday)
    RelativeLayout rlBirthday;
    @BindView(R.id.txt_info_sign)
    TextView txtInfoSign;
    @BindView(R.id.rl_sign)
    RelativeLayout rlSign;
    @BindView(R.id.txt_info_jineng)
    TextView txtInfoJineng;
    @BindView(R.id.rl_jineng)
    RelativeLayout rlJineng;
    @BindView(R.id.switch_button)
    SwitchButton switchButton;

    boolean isInitRut;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_info);
        ButterKnife.bind(this);
        //预先加载仿iOS滚轮实现的全部数据
        mPicker.init(this);
        getLoadDialogAndShow();
        onRequestInfo();

    }



    private void initRut(){

        switchButton.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, final boolean isChecked) {

                HashMap<String, Object> map = new HashMap<>();
                map.put("is_rut", isChecked);
                HttpUtils.getInstance().toSubscribe(Api.getInstance().UpdataInfoUseInfos(map)
                        , new SimpleSubscriber<HttpResult<UserModel>>() {
                            @Override
                            protected void _onNext(HttpResult<UserModel> o) {

                            }

                            @Override
                            protected void _onError(String message) {

                            }
                        });
            }
        });
    }

    @Override
    protected View setLoadingWrapView() {
        return findViewById(R.id.parent_layout);
    }

    @Override
    protected void onResume() {
        super.onResume();
        onRequestInfo();
    }

    private void onRequestInfo() {
        HttpUtils.getInstance().toSubscribe(Api.getInstance().getUseInfo()
                , new SimpleSubscriber<HttpResult<UserModel>>() {
                    @Override
                    protected void _onNext(HttpResult<UserModel> o) {

                        getLoadDialogAndDismiss();
                        showContent();

                        if (o != null && o.getData() != null) {

                            final UserModel model = o.getData();

                            Hawk.put(MyConfig.SP_CACHE_USERMODEL, model);
                            txtInfoAddress.setText(model.address_home);
                            txtInfoWorkaddress.setText(model.address_company);
                            txtInfoSex.setText(model.gender == 2 ? "女" : "男");
                            txtInfoBirthday.setText(model.age);
                            txtInfoName.setText(model.name);
                            txtInfoSign.setText(model.intro);
                            txtInfoJineng.setText(model.skills);
                            switchButton.setChecked(model.is_rut);
                            initRut();
                            ImageUtils.loadImage(MeInfoActivity.this, model.avatar_url, meInfoAvatar);
                            ageType = model.gender;

                            RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {

                                @Override
                                public UserInfo getUserInfo(String userId) {

                                    UserInfo info = new UserInfo(model.id, model.name, Uri.parse(model.avatar_url));
                                    return info;
                                }
                            }, true);
                        }
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });


    }


    private void onUpdateInfo(Map<String, String> map) {
        HttpUtils.getInstance().toSubscribe(Api.getInstance().UpdataInfoUseInfo(map)
                , new SimpleSubscriber<HttpResult<UserModel>>() {
                    @Override
                    protected void _onNext(HttpResult<UserModel> o) {

                        onRequestInfo();
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });
    }


    private void initPopList(final PopupWindow popupWindow, View popupView) {

        popupView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (popupWindow != null) {

                    popupWindow.dismiss();
                }

            }
        });

        RecyclerView listAddress = popupView.findViewById(R.id.list_address);
        final List<String> list = new ArrayList<>();
        list.add("琴亭镇");
        list.add("坊楼镇");
        list.add("良坊镇");
        list.add("路口镇");
        list.add("升坊镇");
        list.add("湖上乡");
        list.add("神泉乡");
        list.add("三板桥乡");
        list.add("南岭乡");
        list.add("荷塘乡");
        list.add("闪石乡");
        list.add("高洲乡");
        list.add("六市乡");
        homeAdapter = new AddressAdapter(R.layout.item_address, list);
        listAddress.setLayoutManager(new LinearLayoutManager(this));
        homeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                String address = list.get(position);
                txtInfoAddress.setText(address);

                HashMap<String, String> map = new HashMap<>();
                map.put("address_home", address);
                onUpdateInfo(map);
                popupWindow.dismiss();
            }
        });
        listAddress.setAdapter(homeAdapter);
    }


    private void onAddress() {
        View popupView = LayoutInflater.from(MeInfoActivity.this).inflate(R.layout.layout_pop_address, null);
        PopupWindow popupWindow = showPopWindow(popupView, findViewById(R.id.parent_layout));
        initPopList(popupWindow, popupView);
    }


    private void onSex() {

        View popupView = LayoutInflater.from(MeInfoActivity.this).inflate(R.layout.layout_pop_sex, null);
        final PopupWindow popupWindow = showPopWindow(popupView, findViewById(R.id.parent_layout));
        View man = popupView.findViewById(R.id.txt_sex_man);
        View women = popupView.findViewById(R.id.txt_sex_women);
        man.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                txtInfoSex.setText("男");
                HashMap<String, String> map = new HashMap<>();
                map.put("gender", "1");
                onUpdateInfo(map);
                if (popupWindow != null) {

                    popupWindow.dismiss();
                }
            }
        });
        women.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                txtInfoSex.setText("女");
                HashMap<String, String> map = new HashMap<>();
                map.put("gender", "2");
                onUpdateInfo(map);
                if (popupWindow != null) {

                    popupWindow.dismiss();
                }
            }
        });

        popupView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (popupWindow != null) {

                    popupWindow.dismiss();
                }

            }
        });
    }

    @OnClick({R.id.me_info_avatar_lay, R.id.rl_jineng, R.id.rl_info_sex, R.id.rl_address, R.id.rl_workaddress, R.id.rl_name, R.id.rl_sign})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.me_info_avatar_lay:

                selectSingPic();
                break;
            case R.id.rl_info_sex:

                onSex();
                break;

            case R.id.rl_jineng:

                Intent intentJineng = new Intent(this, UpdateInfoActivity.class);
                intentJineng.putExtra("name", txtInfoJineng.getText().toString());
                intentJineng.putExtra("from", "jineng");
                startActivity(intentJineng);
                break;
            case R.id.rl_address:
                onAddress();
                break;

            case R.id.rl_workaddress:
                onCity();
                break;

            case R.id.rl_sign:
                Intent intents = new Intent(this, UpdateInfoActivity.class);
                intents.putExtra("name", txtInfoSign.getText().toString());
                intents.putExtra("from", "sign");
                startActivity(intents);
                break;

            case R.id.rl_name:

                Intent intent = new Intent(this, UpdateInfoActivity.class);
                intent.putExtra("name", txtInfoName.getText().toString());
                startActivity(intent);

                break;
        }
    }


    private void onCity() {


        //添加默认的配置，不需要自己定义，当然也可以自定义相关熟悉，详细属性请看demo
        CityConfig cityConfig = new CityConfig.Builder().build();
        cityConfig.setConfirmTextColorStr("#f6533e");
        cityConfig.setCancelTextColorStr("#f6533e");
        mPicker.setConfig(cityConfig);

//监听选择点击事件及返回结果
        mPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {

                txtInfoWorkaddress.setText(province.getName() + " " + city.getName() + " " + district.getName());
                //省份province
                //城市city
                //地区district

                HashMap<String, String> map = new HashMap<>();
                map.put("address_company", province.getName() + " " + city.getName() + " " + district.getName());
                onUpdateInfo(map);
            }

            @Override
            public void onCancel() {
                ToastUtils.showLongToast(MeInfoActivity.this, "已取消");
            }
        });

        //显示
        mPicker.showCityPicker();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> localMedias = PictureSelector.obtainMultipleResult(data);
                    if (localMedias != null && localMedias.size() > 0) {

                        if (NetworkUtil.isNetworkConnected(this)) {


                            Glide.with(MeInfoActivity.this)
                                    .load(localMedias.get(0).getPath())
                                    .into(meInfoAvatar);

                            List<ImageModel> models = new ArrayList<>();
                            ImageModel model = new ImageModel();
                            model.imgPath = localMedias.get(0).getCutPath();
                            models.add(model);
                            QiNiuUtils.getInstance().initImage(models, handler);
                        } else {

                        }
                    }
                    break;
            }
        }
    }


    Date mCurDate;

    /**
     * 选择日期
     */
    public void onDate() {

        TimePickerView pvTime;
        //时间选择器 ，自定义布局
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(selectedDate.get(Calendar.YEAR) - 80, 0, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(selectedDate.get(Calendar.YEAR), 11, 28);


        if (mCurDate != null) {
            selectedDate.setTime(mCurDate);
        } else {
            Calendar init = Calendar.getInstance();
            init.set(init.get(Calendar.YEAR) - 23, 11, 28);
            selectedDate.setTime(init.getTime());
        }
        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调

                mCurDate = date;
                int age = (new Date().getYear() - date.getYear());
                HashMap<String, String> map = new HashMap<>();
                txtInfoBirthday.setText(age + "");
                map.put("age", age + "");
                onUpdateInfo(map);
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "", "", "")
                .isCenterLabel(false)
                .setDividerColor(Color.parseColor("#dddddd"))
                .setCancelColor(Color.parseColor("#666666"))
                .setSubmitColor(Color.parseColor("#666666"))
                .setContentTextSize(21)
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setBackgroundId(0x00FFFFFF) //设置外部遮罩颜色
                .setDecorView(null)
                .build();
        pvTime.show();

    }

    public String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            List<ImageModel> list = (List<ImageModel>) msg.obj;

            if (list != null && list.size() > 0) {

                HashMap<String, String> map = new HashMap<>();
                map.put("avatar_url", list.get(0).uploadPath);
                onUpdateInfo(map);
            }
        }
    };


    @OnClick(R.id.rl_birthday)
    public void onViewClicked() {

        onDate();
    }


}

